package com.czk.server;

import com.czk.domain.FileTransferProtocol;
import com.czk.utils.FileUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/6/1 14:13
 */
public class MyServerHandler extends ChannelInboundHandlerAdapter {
    private ChannelHandlerContext ctx;
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端连接成功");
        this.ctx = ctx;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FileTransferProtocol) {
            // 强转
            FileTransferProtocol fileTransferProtocol = (FileTransferProtocol) msg;
            // 拿到数据
            FileUtils.writeFile("E:\\"+fileTransferProtocol.getFileName(), fileTransferProtocol);
            this.ctx.writeAndFlush("写入成功");
        }else {
            System.out.println("写入失败");
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

}
}
